<template>
  <view>
    <view
      :style="{
        height: statusBarHeight + 'px',
        backgroundColor: backgroundColor,
      }"
    ></view>
    <web-view :src="webViewUrl" @message="getMessage"></web-view>
  </view>
</template>

<script>
let _self;
export default {
  computed: {
    // ...mapGetters(["shareData"]),
  },
  props: {
    dataSource: {
      type: Object,
      default: () => {
        return { url: "" };
      },
    },
  },
  data() {
    return {
      webViewUrl: "",
      statusBarHeight: 0,
      backgroundColor: "#fff",
      currentWebview: null,
    };
  },
  watch: {
    dataSource: {
      handler(val, oldVal) {
        if (val.url) {
          _self = this;
          this.initialization(val);
        }
      },
      immediate: true,
      deep: true, // 监听这个对象中的每一个属性变化
    },
  },
  onLoad(options) {
    _self = this;
    this.initialization(options);
  },
  mounted() {
    // #ifdef APP-PLUS
    _self.currentWebview = _self.$scope.$getAppWebview().children()[0];
    // 获取手机系统信息
    const info = uni.getSystemInfoSync();
    // 设置状态栏高度（H5顶部无状态栏小程序有状态栏需要撑起高度）
    _self.statusBarHeight = info.statusBarHeight;
    //设置高度样式
    _self.currentWebview.setStyle({
      top: _self.statusBarHeight,
      height: info.windowHeight - _self.statusBarHeight,
      scalable: false, //webview的页面是否可以缩放，双指放大缩小
    });
    // #endif
  },
  methods: {
    initialization(options) {
      _self = this;
      if (options && options.url) {

        _self.webViewUrl = decodeURIComponent(options.url);
        console.log("webViewUrl", _self.webViewUrl);
        // 分享内容
        // if (_self.shareData.type == "MDSC_shareData") {
        //   _self.webViewUrl += `&shareData=${encodeURIComponent(
        //     JSON.stringify(_self.shareData)
        //   )}`;
        //   let jsonForm = {
        //     id: "",
        //     userId: "",
        //     type: "",
        //   };
        //   // 同步store
        //   store.commit("setShareData", jsonForm);
        // }
      }
      if (options.backgroundColor) {
        _self.backgroundColor = decodeURIComponent(options.backgroundColor);
      }
    },
    loadList() {},
    getMessage(event) {
      console.log(event);
      let messageData = event.detail.data[0];
      //返回上一页面
      if (messageData.api == "navigateBack") {
        uni.navigateBack();
      }
      //跳转至非table页面
      if (messageData.api == "navigateTo") {
        uni.navigateTo({
          url: messageData.url,
        });
      }
      // 支付
      if (messageData.api == "pay") {
        // payObj {
        // 	"pay": {
        // 		"data": "",//调起支付的参数
        // 		"payType": "3"//支付类型
        // 	}
        // }
        // let payObj = event.detail.data[0].pay;
        // _self.KingonUI.Core.AlipayOrWxpayNewToPay(payObj.payType, payObj.data, (res) => {
        // 	// 向H5页面发送消息
        // 	_self.currentWebview.evalJS(`postJS(${JSON.stringify(res)})`);
        // });
      }
      // 分享
      if (messageData.api == "share") {
        let shareObj = messageData.data;
        // 微信小程序版本类型，可取值： 0-正式版； 1-测试版； 2-体验版。 默认值为0。
        // shareObj.miniProgram.type = 2;
        //获取图片后压缩。type为0时，推荐使用小于20Kb的图片
        uni.downloadFile({
          url: shareObj.imageUrl,
          success: (images) => {
            uni.compressImage({
              src: images.tempFilePath,
              quality: 20,
              width: "60%",
              height: "60%",
              success: (res) => {
                uni.share({
                  provider: shareObj.provider,
                  scene: shareObj.scene,
                  type: shareObj.type,
                  title: shareObj.title,
                  href: shareObj.href,
                  imageUrl: res.tempFilePath,
                  miniProgram: shareObj.miniProgram,
                  success: function (res) {
                    _self.currentWebview.evalJS(
                      `postJS(${JSON.stringify(res)})`
                    );
                  },
                  fail: function (err) {
                    uni.showToast({
                      icon: "none",
                      title: `分享失败，${err.errMsg}`,
                    });
                    console.log("fail:" + JSON.stringify(err));
                  },
                });
              },
            });
          },
        });
      }
      // 复制粘贴板
      if (messageData.api == "clipboardData") {
        let obj = event.detail.data[0].clipboardData;
        if (obj.type == "get") {
          uni.getClipboardData({
            success: (res) => {
              if (!res.data) return;
              _self.currentWebview.evalJS(
                `openModal(${JSON.stringify(res.data)})`
              );
            },
          });
        } else if (obj.type == "set") {
          uni.setClipboardData({
            data: obj.data || "",
            success: () => {
              console.log("success");
              uni.hideToast();
            },
          });
        }
      }
      // 获取定位
      if (messageData.api == "getLocation") {
        // _self.KingonUI.Core.GetLocation(function (location) {
        // 	// address = location.address;
        // 	// longitude: res.longitude,
        // 	// latitude: res.latitude,
        // 	// 向H5页面发送消息
        // 	_self.currentWebview.evalJS(`postJS(${JSON.stringify(location)})`);
        // });
      }
      //扫码
      if (messageData.api == "scanCode") {
        uni.scanCode({
          success: function (res) {
            _self.currentWebview.evalJS(`postJS(${JSON.stringify(res)})`);
          },
        });
      }
      //是否开启直播
      if (messageData.api == "liveBroadcast") {
        let deptId = "";
        if (event.detail.data[0].deptId) deptId = event.detail.data[0].deptId;
        uni.navigateTo({
          url:
            "/subHome/public/liveBroadcastFunciton/liveBroadcast/index?deptId=" +
            deptId,
        });
      }
      //是否观看直播
      if (event.detail.data[0].liveBroadcastCenter) {
        uni.navigateTo({
          url: "/subHome/public/liveBroadcastFunciton/LiveBroadcastCenter/index",
        });
      }
      // 保持图片到手机
      if (messageData.api == "saveImageToPhotosAlbum") {
        let base64 = messageData.data;
        const bitmap = new plus.nativeObj.Bitmap("test");
        bitmap.loadBase64Data(
          base64,
          function () {
            const url = "_doc/" + new Date().getTime() + ".png"; // url为时间戳命名方式
            console.log("saveHeadImgFile", url);
            bitmap.save(
              url,
              {
                overwrite: true, // 是否覆盖
                // quality: 'quality'  // 图片清晰度
              },
              (i) => {
                uni.saveImageToPhotosAlbum({
                  filePath: url,
                  success: function () {
                    uni.showToast({
                      title: "图片保存成功",
                      icon: "none",
                    });
                    bitmap.clear();
                  },
                });
              },
              (e) => {
                uni.showToast({
                  title: "图片保存失败",
                  icon: "none",
                });
                bitmap.clear();
              }
            );
          },
          (e) => {
            uni.showToast({
              title: "图片保存失败",
              icon: "none",
            });
            bitmap.clear();
          }
        );
      }
      //拨打电话
      if (messageData.api == "phoneCall") {
        uni.makePhoneCall({
          phoneNumber: messageData.phoneNumber, //仅为示例
        });
      }
    },
    setUrlHash: function (url, hash) {
      if (null == url || "" === (url = String(url).trim())) return url;
      let hashIndex = url.indexOf("#");
      let urlWithoutQueryAndHash;
      if (-1 == hashIndex) {
        urlWithoutQueryAndHash = url;
      } else {
        urlWithoutQueryAndHash = url.substring(0, hashIndex);
      }
      return urlWithoutQueryAndHash + "#" + hash;
    },
    getWebviewSrc: function () {
      let pages = getCurrentPages();
      let page = pages[pages.length - 1];
      return page.data.url;
    },
    setWebviewSrc: function (url) {
      let pages = getCurrentPages();
      let page = pages[pages.length - 1];
      page.setData({
        url: url,
      });
    },
  },
};
</script>

<style></style>
